package com.initialize.appapi.triggertask;

import cn.hutool.http.HttpRequest;
import com.initialize.pub.mybatis.plus.entity.BingImg;
import com.initialize.pub.mybatis.plus.mapper.BingImgMapper;
import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;


/**
 *
 */
@Component
@Configuration
@EnableScheduling
public class DynamicScheduleTask {

    Logger log = LoggerFactory.getLogger(DynamicScheduleTask.class);


    @Autowired
    BingImgMapper bingImgMapper;

    /**
     * 每天采集必应的图片
     */
    @Scheduled(cron = "0 0 4 * * ? ")
    public void scheduled() {
        BingImg bingImg = new BingImg();

        String body = HttpRequest.get("https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=" + 1 + "&mkt=zh-CN")
                .timeout(10000)
                .execute().body();
        try {
            org.json.JSONArray images1 = new org.json.JSONObject(body).getJSONArray("images");
            String s = images1.get(0).toString();
            org.json.JSONObject jsonObject1 = new org.json.JSONObject(s);
            String url = jsonObject1.get("url").toString();
            String urlbase = jsonObject1.get("urlbase").toString();
            String copyright = jsonObject1.get("copyright").toString();
            String title = jsonObject1.get("title").toString();

            bingImg.setCopyright(copyright);
            bingImg.setUrlbase(urlbase);
            LocalDateTime localDateTime =  LocalDateTime.now();
            bingImg.setAddtime(localDateTime);
            bingImg.setTitle(title);
            bingImg.setUrl("https://cn.bing.com"+url);

            bingImgMapper.insert(bingImg);
            log.info("----完成当日的必应图片采集");
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }


}